package com.iot.iotplus.controller;

import com.iot.iotplus.base.Result;
import com.iot.iotplus.base.vo.AuthVO;
import com.iot.iotplus.base.vo.DirectiveVO;
import com.iot.iotplus.base.vo.MqttVO;
import com.iot.iotplus.service.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

//设备认证接口
@RestController
@RequestMapping("/auth")
public class AuthenticationController {
    @Autowired
    private AuthenticationService authenticationService;

    @PostMapping("/login")
    public AuthVO<MqttVO> deviceAuth(@RequestBody Map<String,String> map){
        Result<?> result = authenticationService.checkAuth(map.get("productKey"), map.get("deviceKey"), map.get("deviceSecret"));
        AuthVO<MqttVO> vo = null;
        if (result.getCode() == 200){
            MqttVO mqttVO = new MqttVO();
            mqttVO.setProductKey(map.get("productKey"));
            mqttVO.setDeviceKey(map.get("deviceKey"));
            mqttVO.setDeviceSecret(map.get("deviceSecret"));
            mqttVO.setUrl("tcp:47.98.63.69");
            mqttVO.setIp("47.98.63.69");
            mqttVO.setPort(1883);
            mqttVO.setUsername((String) result.getData());
            mqttVO.setPassword((String) result.getData());
            mqttVO.setTenantId((String) result.getData());
            vo = new AuthVO<>(true,200,"ok",mqttVO);
        }
        return vo;
    }

    @PostMapping("/pub")
    public Result<?> publish(@RequestHeader Map<String,String> handMap,@RequestBody DirectiveVO directive){
        String accessKey = handMap.get("access-key");
        String accessSecurity = handMap.get("access-security");
        String sign = handMap.get("sign");
        return authenticationService.publish(accessKey,accessSecurity,sign,directive);
    }

}
